<?php

namespace App\Http\Controllers\Api\Admin;

use App\Classify;
use App\Comment;
use App\Experts;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\InvoiceLookUp;
use App\InvoiceRecord;
use App\PersonalAuth;
use App\Role;
use App\UnitAuth;
use App\UnitBusinessLabel;
use App\UnitGrade;
use App\Units;
use App\UnitSettledApply;
use App\UserInfo;
use App\UserXUnit;
use http\Client\Curl\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class UnitController extends Controller
{
    /**
     * 单位入驻申请列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitSettledApplyList(Request $request){
        $page      = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit     = !is_null($request->get('limit'))? $request->get('limit'): 10;
        $status    = !is_null($request->get('status')) ? $request->get('status') : 'default';
        $id        = !is_null($request->get('id')) ? $request->get('id') : 0;

        $pageInfo = [
            'page' => $page,
            'limit' => $limit,
        ];

        /** @var UnitSettledApply $unitSettledApply */
        $unitSettledApplyList = UnitSettledApply::whereNull('deleted_at');

        if($status != 'default' && $status !== ''){
            $unitSettledApplyList->whereStatus($status);
        }

        if($id != ''){
            $unitSettledApplyList = $unitSettledApplyList->whereId($id);
        }

        $pageInfo['total'] = $unitSettledApplyList->count();

        $unitSettledApplyList = $unitSettledApplyList->orderBy('is_top','desc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($unitSettledApplyList) > 0){
            foreach($unitSettledApplyList as $unitSettledApply){
//                $userInfo = CommonManager::getUserBasicInfo($unitSettledApply->user_id);
                $unitSettledApply->photo_url = FileManager::getImgUrl($unitSettledApply->photo_id);
                $unitSettledApply->unit_business_label = CommonManager::getUnitBusinessLabel($unitSettledApply->id);
                $unitSettledApply->auth_status = CommonManager::getAuthReviewStatus($unitSettledApply->status);
                $unitSettledApply->license_img_url = FileManager::getImgUrl($unitSettledApply->license_img_id);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $unitSettledApplyList,'page_info' => $pageInfo]);
    }

    /**
     * 改变入驻申请的状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeUnitSettledApplyStatus(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;
        $type = !is_null($request->get('type')) ? $request->get('type') : 'default';

        $unitSettledApply = UnitSettledApply::whereId($id)->first();
        if(!$unitSettledApply)
            return response()->json(['level' => 'error','message' => '入驻申请不存在']);

        if($type == 'default'){
            if($unitSettledApply->status == 1)
                return response()->json(['level' => 'error','message' => '申请已通过']);

            if($unitSettledApply->status == 2)
                return response()->json(['level' => 'error','message' => '申请已拒绝']);

            $unitSettledApply->status = 1;

            $unit = Units::whereUniformSocialCreditCode($unitSettledApply->uniform_social_credit_code)->first();
            if(!$unit)
                $unit = new Units();

            if($unit->is_member_unit == 1)
                return response()->json(['level' => 'error','message' => '该单位已是会员单位']);

            $unit->is_member_unit                = 1;
            $unit->name                          = $unitSettledApply->name;
            $unit->province                      = $unitSettledApply->province;
            $unit->city                          = $unitSettledApply->city;
            $unit->area                          = $unitSettledApply->area;
            $unit->address                       = $unitSettledApply->address;
            $unit->license_img_id                = $unitSettledApply->license_img_id;
            $unit->uniform_social_credit_code    = $unitSettledApply->uniform_social_credit_code;
            $unit->legal_person_name             = $unitSettledApply->legal_person_name;
            $unit->contact_number                = $unitSettledApply->contact_number;
            $unit->photo_id                      = $unitSettledApply->photo_id;
            $unit->introduction                  = $unitSettledApply->introduction;
            $unit->save();

            $unitBusinessList = UnitBusinessLabel::whereUnitSettledApplyId($unitSettledApply->id)->get();
            if(count($unitBusinessList) > 0){
                foreach ($unitBusinessList as $item) {
                    $item->unit_id = $unit->id;
                    $item->save();
                }
            }

            UserXUnit::whereUserId($unitSettledApply->user_id)->where('unit_id','<>',$unit->id)->delete();

            if($unitSettledApply->is_unit_admin == 1){
                $thisUserXUnit = UserXUnit::whereUserId($unitSettledApply->user_id)->whereUnitId($unit->id)->first();
                if($thisUserXUnit && $thisUserXUnit->is_admin != 1){
                    $thisUserXUnit->is_admin = 1;
                    $thisUserXUnit->save();
                }else{
                    $newUserXUnit = new UserXUnit();
                    $newUserXUnit->user_id  = $unitSettledApply->user_id;
                    $newUserXUnit->unit_id  = $unit->id;
                    $newUserXUnit->is_admin = 1;
                    $newUserXUnit->save();
                }
            }else{
                $thisUserXUnit = UserXUnit::whereUserId($unitSettledApply->user_id)->whereUnitId($unit->id)->first();
                if(!$thisUserXUnit){
                    $newUserXUnit = new UserXUnit();
                    $newUserXUnit->user_id  = $unitSettledApply->user_id;
                    $newUserXUnit->unit_id  = $unit->id;
                    $newUserXUnit->save();
                }
            }

            $userXUnitList = UserXUnit::whereUnitId($unit->id)->get();
            if(count($userXUnitList) > 0){
                foreach($userXUnitList as $userXUnit){
                    $isUser = \App\User::whereId($userXUnit->user_id)->first();
                    if($isUser){
                        DB::table('role_user')->where('user_id',$userXUnit->user_id)->delete();

                        if($userXUnit->is_admin == 1){
                            $role = Role::whereName('vip_unit_admin')->first();
                            if($role){
                                DB::table('role_user')->insert(['user_id' => $userXUnit->user_id,'role_id' => $role->id]);
                            }
                        }else{
                            $role = Role::whereName('vip_unit_staff')->first();
                            if($role){
                                DB::table('role_user')->insert(['user_id' => $userXUnit->user_id,'role_id' => $role->id]);
                            }
                        }
                    }
                }
            }

            $thisUser = \App\User::whereId($unitSettledApply->user_id)->first();
            if($thisUser){
                WechatLogin::weSendSubscribeMessage('company_set',$thisUser->wx_openid,0,$unitSettledApply->name,'您的企业认证已通过',date("Y-m-d H:i:s",time()));
            }
        }elseif($type == 'refusal'){
            if($unitSettledApply->status == 1)
                return response()->json(['level' => 'error','message' => '申请已通过']);

            if($unitSettledApply->status == 2)
                return response()->json(['level' => 'error','message' => '申请已拒绝']);

            $unitSettledApply->status = 2;

            $thisUser = \App\User::whereId($unitSettledApply->user_id)->first();
            if($thisUser){
                WechatLogin::weSendSubscribeMessage('company_set',$thisUser->wx_openid,0,$unitSettledApply->name,'您的企业认证被拒绝',date("Y-m-d H:i:s",time()));
            }
        }else{
            return response()->json(['level' => 'error','message' => '操作类型不正确']);
        }

        $unitSettledApply->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $unitSettledApply]);
    }

    /**
     * 删除入驻申请
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delUnitSettledApply(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $unitSettledApply = UnitSettledApply::whereId($id)->first();
        if(!$unitSettledApply)
            return response()->json(['level' => 'error','message' => '入驻申请不存在']);

        $unitSettledApply->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $unitSettledApply]);
    }

    /**
     * 获取官方单位信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOfficialUnitInfo(Request $request){
        $officialUnitInfo = Units::whereIsMemberUnit(2)->first();
        if($officialUnitInfo){
            $officialUnitInfo->logo_url             = FileManager::getImgUrl($officialUnitInfo->photo_id);
            $officialUnitInfo->unit_business_label  = CommonManager::getUnitBusinessLabel($officialUnitInfo->id);
            $officialUnitInfo->license_img_url      = FileManager::getImgUrl($officialUnitInfo->license_img_id);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $officialUnitInfo]);
    }

    /**
     * 设置官方单位信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setOfficialUnitInfo(Request $request){
        $unitName                 = !is_null($request->get('unit_name')) ? $request->get('unit_name') : '';
        $photoId                  = !is_null($request->get('logo_id')) ? $request->get('logo_id') : 0;
        $uniformSocialCreditCode  = !is_null($request->get('uniform_social_credit_code')) ? $request->get('uniform_social_credit_code') : '';
        $province                 = !is_null($request->get('province')) ? $request->get('province') : '';
        $city                     = !is_null($request->get('city')) ? $request->get('city') : '';
        $area                     = !is_null($request->get('area')) ? $request->get('area') : '';
        $address                  = !is_null($request->get('address')) ? $request->get('address') : '';
        $licenseImgId             = !is_null($request->get('license_img_id')) ? $request->get('license_img_id') : 0;
        $contactNumber            = !is_null($request->get('contact_number')) ? $request->get('contact_number') : '';
        $introduction             = !is_null($request->get('introduction')) ? $request->get('introduction') : '';
        $businessScope            = $request->get('business_scope');

        $thisUnitInfo = Units::whereIsMemberUnit(2)->first();
        if(!$thisUnitInfo){
            $thisUnitInfo = new Units();
            $thisUnitInfo->is_member_unit     = 2;
        }

        if($photoId != 0)$thisUnitInfo->photo_id                                    = $photoId;
        if($unitName != '')$thisUnitInfo->name                                       = $unitName;
        if($uniformSocialCreditCode != '')$thisUnitInfo->uniform_social_credit_code  = $uniformSocialCreditCode;
        if($province != '')$thisUnitInfo->province                                   = $province;
        if($city != '')$thisUnitInfo->city                                           = $city;
        if($area != '')$thisUnitInfo->area                                           = $area;
        if($address != '')$thisUnitInfo->address                                     = $address;
        if($licenseImgId != '')$thisUnitInfo->license_img_id                         = $licenseImgId;
        if($contactNumber != '')$thisUnitInfo->contact_number                        = $contactNumber;
        if($introduction != '')$thisUnitInfo->introduction                           = $introduction;
        if($unitName != '')$thisUnitInfo->save();

        if(is_array($businessScope) && count($businessScope) > 0){
            $unitBusinessLabel = UnitBusinessLabel::whereUnitId($thisUnitInfo->id)->get();
            if(count($unitBusinessLabel) > 0){
                foreach($unitBusinessLabel as $item){
                    $item->forceDelete();
                }
            }

            foreach($businessScope as $val){
                $newUnitBusinessLabel = new UnitBusinessLabel();
                $newUnitBusinessLabel->unit_id          = $thisUnitInfo->id;
                $newUnitBusinessLabel->name             = $val;
                $newUnitBusinessLabel->save();
            }
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $thisUnitInfo]);
    }

    /**
     * 获取单位列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitList(Request $request){
        /** @var \App\User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page         = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit        = !is_null($request->get('limit'))? $request->get('limit'): 10;
        $keyword      = !is_null($request->get('keyword')) ? $request->get('keyword') : '';
        $isMemberUnit = !is_null($request->get('is_member_unit')) ? $request->get('is_member_unit') : 0;
        $classifyId    = !is_null($request->get('classify_id')) ? $request->get('classify_id') : 0;
        $unitGradeId   = !is_null($request->get('unit_grade_id')) ? $request->get('unit_grade_id') : 0;

        $pageInfo = [
            'page' => $page,
            'limit' => $limit,
        ];

        $page = $page - 1;

        $unitId = 0;
        if($adminUser->role == 0){
            $unitAuth = CommonManager::isUnitAuth($adminUser->id);
            if($unitAuth){
                $userXUnit = UserXUnit::whereUserId($adminUser->id)->first();
                if($userXUnit){
                    $unitId = $userXUnit->unit_id;
                }
            }
        }

        $unitList = CommonManager::getAllUnitInfoList('list',$isMemberUnit,$keyword,$limit,$page,0,$unitId,$classifyId,$unitGradeId);

        $pageInfo['total']  = CommonManager::getAllUnitInfoNum($isMemberUnit,$keyword);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $unitList,'page_info' => $pageInfo]);
    }

    /**
     * 获取单位详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitDetail(Request $request){
        $id  = !is_null($request->get('id')) ? $request->get('id') : 0;

        $unit = CommonManager::getAllUnitInfoList('detail',1,'',0,0,$id);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $unit]);
    }

    /**
     * 编辑单位信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editUnitInfo(Request $request){
        $id                       = !is_null($request->get('id')) ? $request->get('id') : 0;
        $unitName                 = !is_null($request->get('unit_name')) ? $request->get('unit_name') : '';
        $photoId                  = !is_null($request->get('logo_id')) ? $request->get('logo_id') : 0;
        $uniformSocialCreditCode  = !is_null($request->get('uniform_social_credit_code')) ? $request->get('uniform_social_credit_code') : '';
        $province                 = !is_null($request->get('province')) ? $request->get('province') : '';
        $city                     = !is_null($request->get('city')) ? $request->get('city') : '';
        $area                     = !is_null($request->get('area')) ? $request->get('area') : '';
        $address                  = !is_null($request->get('address')) ? $request->get('address') : '';
        $licenseImgId             = !is_null($request->get('license_img_id')) ? $request->get('license_img_id') : 0;
        $contactNumber            = !is_null($request->get('contact_number')) ? $request->get('contact_number') : '';
        $introduction             = !is_null($request->get('introduction')) ? $request->get('introduction') : '';
        $businessScope            = $request->get('business_scope');
        $sort                     =  !is_null($request->get('sort'))?$request->get('sort'):0;
        $classifyId               =  !is_null($request->get('classify_id'))?$request->get('classify_id') : 0;
        $unitGradeId              =  !is_null($request->get('unit_grade_id'))?$request->get('unit_grade_id') : 0;

        $thisUnitInfo = Units::whereId($id)->first();
        if(!$thisUnitInfo){
            $thisUnitInfo = new Units();
            $thisUnitInfo->is_member_unit     = 1;
        }

        if($photoId != 0)$thisUnitInfo->photo_id                                    = $photoId;
        if($unitName != '')$thisUnitInfo->name                                       = $unitName;
        if($uniformSocialCreditCode != '')$thisUnitInfo->uniform_social_credit_code  = $uniformSocialCreditCode;
        if($province != '')$thisUnitInfo->province                                   = $province;
        if($city != '')$thisUnitInfo->city                                           = $city;
        if($area != '')$thisUnitInfo->area                                           = $area;
        if($address != '')$thisUnitInfo->address                                     = $address;
        if($licenseImgId != '')$thisUnitInfo->license_img_id                         = $licenseImgId;
        if($contactNumber != '')$thisUnitInfo->contact_number                        = $contactNumber;
        if($introduction != '')$thisUnitInfo->introduction                           = $introduction;
        if($classifyId != 0)$thisUnitInfo->classify_id                               = $classifyId;
        if($unitGradeId != 0)$thisUnitInfo->unit_grade_id                            = $unitGradeId;
        $thisUnitInfo->sort                                                          = $sort;
        $thisUnitInfo->save();

        if(is_array($businessScope) && count($businessScope) > 0){
            $unitBusinessLabel = UnitBusinessLabel::whereUnitId($thisUnitInfo->id)->get();
            if(count($unitBusinessLabel) > 0){
                foreach($unitBusinessLabel as $item){
                    $item->forceDelete();
                }
            }

            foreach($businessScope as $val){
                $newUnitBusinessLabel = new UnitBusinessLabel();
                $newUnitBusinessLabel->unit_id          = $thisUnitInfo->id;
                $newUnitBusinessLabel->name             = $val;
                $newUnitBusinessLabel->save();
            }
        }

        return response()->json(['level' => 'success','message' => '编辑成功','data' => $thisUnitInfo]);
    }

    /**
     * 删除会员单位
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delMemberUnit(Request $request){
        $id           = !is_null($request->get('id')) ? $request->get('id') : 0;

        $memberUnit = Units::whereId($id)->whereIsMemberUnit(1)->first();
        if(!$memberUnit)
            return response()->json(['level' => 'error','message' => '会员单位不存在']);

        $userXUnitList = UserXUnit::whereUnitId($memberUnit->id)->get();
        if(count($userXUnitList) > 0){
            foreach($userXUnitList as $userXUnit){
                $unitAuth = UnitAuth::whereUserId($userXUnit->user_id)->first();
                if($unitAuth){
                    $unitAuth->delete();
                }

                $userXUnit->delete();
            }
        }

        Comment::whereUnitId($memberUnit->id)->delete();

        $memberUnit->delete();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $memberUnit]);
    }

    /**
     * 获取会员单位的官方点评列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMemberUnitOfficialCommentList(Request $request){
        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 1;
        $id    = !is_null($request->get('id')) ? $request->get('id') : 0;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];

        $isMemberUnit = CommonManager::isVipUnitToUnitId($id);
        if(!$isMemberUnit)
            return response()->json(['level' => 'error','message' => '不是会员单位，不能添加官方点评']);

        $page = $page - 1;
        $memberUnitOfficialCommentList = CommonManager::getCommentList($id,'unit',$limit,$page);
        $pageInfo['total'] = CommonManager::getCommentNum($id,'unit');

        return response()->json(['level' => 'success','message' => '获取成功','data' => $memberUnitOfficialCommentList,'page_info' => $pageInfo]);
    }

    /**
     * 获取会员单位的官方点评详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMemberUnitOfficialCommentDetail(Request $request){
        $id    = !is_null($request->get('id')) ? $request->get('id') : 0;

        $memberUnitOfficialCommentList = CommonManager::getCommentDetail($id,'unit');

        return response()->json(['level' => 'success','message' => '湖区成功','data' => $memberUnitOfficialCommentList]);
    }

    /**
     * 设置会员单位的官方点评
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setMemberUnitOfficialComment(Request $request){
        $id      = !is_null($request->get('id')) ? $request->get('id') : 0;
        $unitId  = !is_null($request->get('unit_id')) ? $request->get('unit_id') : 0;
        $content = !is_null($request->get('content')) ? $request->get('content') : '';

        $unit = Units::whereId($unitId)->whereIsMemberUnit(1)->first();
        if(!$unit)
            return response()->json(['level' => 'error','message' => '单位不存在']);

        $memberUnitOfficialComment = Comment::whereId($id)->whereIsOfficial(1)->whereStatus(1)->whereType('unit')->first();
        if(!$memberUnitOfficialComment)
            $memberUnitOfficialComment = new Comment();

        $memberUnitOfficialComment->unit_id     = $unitId;
        $memberUnitOfficialComment->type        = 'unit';
        if($content != '')$memberUnitOfficialComment->content     = $content;
        $memberUnitOfficialComment->is_official = 1;
        $memberUnitOfficialComment->status      = 1;
        $memberUnitOfficialComment->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $memberUnitOfficialComment]);
    }

    /**
     * 删除会员单位的官方点评
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delMemberUnitOfficialComment(Request $request){
        $id      = !is_null($request->get('id')) ? $request->get('id') : 0;

        $memberUnitOfficialComment = Comment::whereId($id)->whereIsOfficial(1)->whereStatus(1)->whereType('unit')->first();
        if(!$memberUnitOfficialComment)
            return response()->json(['level' => 'error','message' => '数据不存在']);

        $memberUnitOfficialComment->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $memberUnitOfficialComment]);
    }

    /**
     * 员工列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitEmployeeList(Request $request){
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $id      = !is_null($request->get('id')) ? $request->get('id') : 0;
        $isAuth  = !is_null($request->get('is_auth')) ? $request->get('is_auth') : 0;
        $keyword = !is_null($request->get('keyword')) ? $request->get('keyword') : '';

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];

        /** @var UserXUnit $unitEmployee */
        $unitEmployeeList = UserXUnit::whereUnitId($id)->whereIsAdmin(0);

        if($isAuth != 0){
            $unit = Units::whereId($id)->first();
            if($unit){
                $userIds = UnitAuth::whereUniformSocialCreditCode($unit->uniform_social_credit_code)->whereIsAuth($isAuth)->pluck('user_id');

                $unitEmployeeList->whereIn('user_id',$userIds);
            }
        }

        if($keyword != ''){
            $userId = \App\User::where('phone','like','%'.trim($keyword).'%')->pluck('id');

            $userInfoUserIds = UserInfo::whereIn('user_id',$userId)->orWhere('nickname','like','%'.trim($keyword).'%')->orWhere('realname','like','%'.trim($keyword).'%')->pluck('user_id');

            $unitEmployeeList = $unitEmployeeList->whereIn('user_id',$userInfoUserIds);
        }

        $pageInfo['total'] = $unitEmployeeList->count();

        $unitEmployeeList = $unitEmployeeList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($unitEmployeeList) > 0){
            foreach($unitEmployeeList as $unitEmployee){
                $userInfo = CommonManager::getUserBasicInfo($unitEmployee->user_id);
                $unitEmployee->realname     = $userInfo ? !is_null($userInfo['realname']) && $userInfo['realname'] != '' ? $userInfo['realname'] : $userInfo['nickname'] : '';
                $unitEmployee->phone        = $userInfo ? $userInfo['phone'] : '';

                $unitAuth = UnitAuth::whereUserId($unitEmployee->user_id)->first();
                if($unitAuth){
                    $unitAuth->license_img_url = FileManager::getImgUrl($unitAuth->license_img_id);
                    $unitAuth->auth_status = CommonManager::getAuthReviewStatus($unitAuth->is_auth);
                }

                $unitEmployee->unit_auth_info = $unitAuth;

                $personalAuth = PersonalAuth::whereUserId($unitEmployee->user_id)->first();
                if($personalAuth){
                    $personalAuth->work_img_url = FileManager::getImgUrl($personalAuth->work_img_id);

                    $personalAuth->is_member_unit = CommonManager::isVipUnitToUserId($unitEmployee->user_id);
                }

                $unitEmployee->personal_auth_info = $personalAuth;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $unitEmployeeList,'page_info' => $pageInfo]);
    }

    /**
     * 获取单位下的审核列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitAuthList(Request $request){
        $page      = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit     = !is_null($request->get('limit')) ? $request->get('limit'): 10;
        $keyword   = !is_null($request->get('keyword')) ? $request->get('keyword') : '';
        $isAuth    = !is_null($request->get('status')) ? $request->get('status') : 'default';
        $unitId    = !is_null($request->get('unit_id')) ? $request->get('unit_id') : 0;

        $pageInfo = [
            'page' => $page,
            'limit' => $limit,
        ];

        $unit = Units::whereId($unitId)->first();
        if(!$unit)
            return response()->json(['level' => 'success','message' => '获取成功','data' => [],'page_info' => $pageInfo]);

        /** @var PersonalAuth $personalAuth */
        $personalAuthLis = PersonalAuth::whereUnitName($unit->name);

        if($keyword != ''){
            $userId = \App\User::where('phone','like','%'.trim($keyword).'%')->pluck('id');

            $userIds = UserInfo::whereIn('user_id',$userId)->orWhere('nickname','like','%'.trim($keyword).'%')->pluck('user_id');

            $personalAuthLis->whereIn('user_id',$userIds)->orWhere('realname','like','%'.trim($keyword).'%');
        }

        if($isAuth != 'default' && $isAuth !== ''){
            $personalAuthLis = $personalAuthLis->whereIsAuth($isAuth);
        }

        $pageInfo['total'] = $personalAuthLis->count();

        $personalAuthList = $personalAuthLis->orderBy('is_top','desc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($personalAuthList) > 0){
            foreach($personalAuthList as $personalAuth){
                $userInfo = CommonManager::getUserBasicInfo($personalAuth->user_id);
                $personalAuth->photo_url = $userInfo ? $userInfo['photo_url'] : '';
                $personalAuth->phone = $userInfo ? $userInfo['phone'] : '';
                $personalAuth->work_img_url = FileManager::getImgUrl($personalAuth->work_img_id);
                $personalAuth->auth_status = CommonManager::getAuthReviewStatus($personalAuth->is_auth);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $personalAuthList,'page_info' => $pageInfo]);

    }

    /**
     * 员工详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitEmployeeDetail(Request $request){
        $id    = !is_null($request->get('id')) ? $request->get('id') : 0;

        $unitEmployee = UserXUnit::whereId($id)->first();
        if($unitEmployee){
            $userInfo = CommonManager::getUserBasicInfo($unitEmployee->user_id);
            $unitEmployee->realname     = $userInfo ? !is_null($userInfo['realname']) && $userInfo['realname'] != '' ? $userInfo['realname'] : $userInfo['nickname'] : '';
            $unitEmployee->phone        = $userInfo ? $userInfo['phone'] : '';
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $unitEmployee]);
    }

    /**
     * 编辑员工信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editUnitEmployeeInfo(Request $request){
        /** @var \App\User $user */
        $user = UserManager::isLogin($request,$front = 1);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录','data' => 'no_login']);

        $realname = !is_null($request->get('realname')) ? $request->get('realname') : '';
        $status   = !is_null($request->get('status')) ? $request->get('status') : 1;
        $id       = !is_null($request->get('id')) ? $request->get('id') : 0;

        $unitEmployee = UserXUnit::whereId($id)->first();
        if(!$unitEmployee)
            return response()->json(['level' => 'error','message' => '员工不存在']);

        $userInfo = UserInfo::whereUserId($unitEmployee->user_id)->first();
        if(!$userInfo)
            return response()->json(['level' => 'error','message' => '用户信息不存在']);

        $unitAuth = UnitAuth::whereUserId($unitEmployee->user_id)->first();
        if(!$unitAuth)
            return response()->json(['level' => 'error','message' => '认证信息不存在']);

        $personalAuth = PersonalAuth::whereUserId($unitEmployee->user_id)->first();
        if(!$personalAuth)
            return response()->json(['level' => 'error','message' => '认证信息不存在']);

        if($realname != '')$userInfo->realname  = $realname;
        $userInfo->save();

        $unitAuth->is_auth   = $status;
        $unitAuth->auth_time = date("Y-m-d H:i:s",time());
        $unitAuth->save();

        $realname = '';
        if($user->role != 1){
            $userInfo = UserInfo::whereUserId($user->id)->first();
            if($userInfo){
                if($userInfo->realname != '' && !is_null($userInfo->realname)){
                    $realname = $userInfo->realname;
                }else{
                    $realname = $userInfo->nickname;
                }
            }
        }else{
            $realname = $user->admin_name;
        }

        $personalAuth->operator  = $realname;
        $personalAuth->is_auth   = $status;
        $personalAuth->auth_time = date("Y-m-d H:i:s",time());

        $personalAuth->save();

        return response()->json(['level' => 'success','message' => '设置成功']);
    }

    /**
     * 获取单位管理员列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitAdminList(Request $request){
        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 1;
        $id    = !is_null($request->get('id')) ? $request->get('id') : 0;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];

        /** @var UserXUnit $unitAdmin */
        $unitAdminList = UserXUnit::whereUnitId($id)->whereIsAdmin(1);

        $pageInfo['total'] = $unitAdminList->count();

        $unitAdminList = $unitAdminList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($unitAdminList) > 0){
            foreach($unitAdminList as $unitAdmin){
                $userInfo = CommonManager::getUserBasicInfo($unitAdmin->user_id);
                $unitAdmin->realname     = $userInfo ? !is_null($userInfo['realname']) && $userInfo['realname'] != '' ? $userInfo['realname'] : $userInfo['nickname'] : '';
                $unitAdmin->phone        = $userInfo ? $userInfo['phone'] : '';
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $unitAdminList,'page_info' => $pageInfo]);
    }

    /**
     * 添加单位管理员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addUnitAdmin(Request $request){
        $userId = !is_null($request->get('user_id')) ? $request->get('user_id') : 0;
        $unitId = !is_null($request->get('unit_id')) ? $request->get('unit_id') : 0;

        $user = \App\User::whereId($userId)->first();
        if(!$user)
            return response()->json(['level' => 'error','message' => '用户不存在']);

        $userInfo = CommonManager::getUserBasicInfo($userId);

        $unit = Units::whereId($unitId)->first();
        if(!$unit)
            return response()->json(['level' => 'error','message' => '单位不存在']);

        $UserXUnit = UserXUnit::whereUserId($userId)->first();
        if($UserXUnit && $UserXUnit->unit_id != $unitId)
            return response()->json(['level' => 'error','message' => '该用户是别家单位员工']);

        if($UserXUnit && $UserXUnit->unit_id == $unitId && $UserXUnit->is_admin == 1)
            return response()->json(['level' => 'error','message' => '该用户已是管理员']);

        if($UserXUnit){
            $UserXUnit->is_admin = 1;
            $UserXUnit->save();
        }else{
            $newUserXUnit = new UserXUnit();
            $newUserXUnit->user_id  = $userId;
            $newUserXUnit->unit_id  = $unitId;
            $newUserXUnit->is_admin = 1;
            $newUserXUnit->save();

            $newUnitAuth = new UnitAuth();
            $newUnitAuth->user_id                     = $user->id;
            $newUnitAuth->name                        = $unit->name;
            $newUnitAuth->realname                    = $userInfo ? $userInfo['realname'] : '';
            $newUnitAuth->uniform_social_credit_code  = $unit->uniform_social_credit_code;
            $newUnitAuth->province                    = $unit->province;
            $newUnitAuth->city                        = $unit->city;
            $newUnitAuth->area                        = $unit->area;
            $newUnitAuth->address                     = $unit->address;
            $newUnitAuth->license_img_id              = $unit->license_img_id;
            $newUnitAuth->is_auth                     = 1;
            $newUnitAuth->save();
        }

        DB::table('role_user')->where('user_id',$user->id)->delete();

        $role = Role::whereName('vip_unit_admin')->first();
        if($role){
            DB::table('role_user')->insert(['user_id' => $user->id,'role_id' => $role->id]);
        }

        return response()->json(['level' => 'success','message' => '设置成功']);
    }

    /**
     * 删除单位员工或管理员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delUnitEmployee(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $unitEmployee = UserXUnit::whereId($id)->first();
        if(!$unitEmployee)
            return response()->json(['level' => 'error','message' => '删除失败']);

        $UnitAuth = UnitAuth::whereUserId($unitEmployee->user_id)->first();
        if($UnitAuth){
            $UnitAuth->delete();
        }

        $personAuth = PersonalAuth::whereUserId($unitEmployee->user_id)->first();
        if($personAuth){
            $personAuth->delete();
        }

        $unitEmployee->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $unitEmployee]);
    }

    /**
     * 获取单位分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitClassifyList(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page       =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit      =!is_null($request->get('limit')) ? $request->get('limit') : 10;

        $page_info=[
            'page'  => $page,
            'limit' => $limit
        ];

        $classify=Classify::whereType('unit')->orderBy('sort','asc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        $page_info['total']=Classify::whereType('unit')->count();
        return response()->json(['level'=>'success','message'=>'获取成功','page_info'=>$page_info,'data'=>$classify]);
    }

    /**
     * 获取单位分类详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitClassifyDetail(Request $request){
        $id     = !is_null($request->get('id')) ? $request->get('id') : 0;

        $classify = Classify::whereId($id)->first();

        return response()->json(['level'=>'success','message'=>'获取成功','data'=> $classify]);
    }

    /**
     * 设置单位分裂
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setUnitClassify(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $name   = !is_null($request->get('name')) ? $request->get('name') : '';
        $pid    = !is_null($request->get('pid')) ? $request->get('pid') : 0;
        $sort   = !is_null($request->get('sort')) ? $request->get('sort') : 0;
        $id     = !is_null($request->get('id')) ? $request->get('id') : 0;

        if (!$name)
            return response()->json(['level'=>'error','message'=>'请输入分类名称']);

        $classify = Classify::whereId($id)->first();

        $exist  =Classify::whereName($name)->whereType('unit')->first();

        if($classify && ($exist && $classify->id != $exist->id))
            return response()->json(['level' => 'error','message' => '该名称已存在']);

        if (!$classify){
            if ($exist)
                return response()->json(['level'=>'error','message'=>'该名称已存在']);

            $classify       =new Classify();
        }

        $classify->name    = $name;
        $classify->pid     = $pid;
        $classify->sort    = $sort;
        $classify->type    = 'unit';
        $classify->is_show =1;
        $classify->save();
        return response()->json(['level'=>'success','message'=>'操作成功']);
    }

    /**
     * 删除单位分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delUnitClassify(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id     = !is_null($request->get('id')) ? $request->get('id') : 0;

        $classify = Classify::whereId($id)->first();
        if (!$classify)
            return response()->json(['level'=>'error','message'=>'该分类不存在']);

        $classify->delete();

        return response()->json(['level'=>'success','message'=>'删除成功']);
    }

    /**
     * 获取单位等级列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitGradeList(Request $request){
        $page       =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit      =!is_null($request->get('limit')) ? $request->get('limit') : 10;

        $page_info = [
            'page'  => $page,
            'limit' => $limit
        ];

        $unitGradeList = UnitGrade::whereNull('deleted_at');

        $page_info['total'] = $unitGradeList->count();

        $unitGradeList = $unitGradeList->orderBy('level','asc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $unitGradeList,'page_info' => $page_info]);
    }

    /**
     * 获取单位登等级详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUnitGradeDetail(Request $request){
        $id     = !is_null($request->get('id')) ? $request->get('id') : 0;

        $unitGrade = UnitGrade::whereId($id)->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $unitGrade]);
    }

    /**
     * 设置单位等级
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setUnitGrade(Request $request){
        $name   = !is_null($request->get('name')) ? $request->get('name') : '';
        $level  = !is_null($request->get('level')) ? $request->get('level') : 0;
        $id     = !is_null($request->get('id')) ? $request->get('id') : 0;

        if (!$name)
            return response()->json(['level'=>'error','message'=>'请输入分类名称']);

        $UnitGrade = UnitGrade::whereId($id)->first();

        $exist  =UnitGrade::whereName($name)->first();

        if($UnitGrade && ($exist && $UnitGrade->id != $exist->id))
            return response()->json(['level' => 'error','message' => '该名称已存在']);

        if (!$UnitGrade){
            if ($exist)
                return response()->json(['level'=>'error','message'=>'该名称已存在']);

            $UnitGrade       =new UnitGrade();
        }

        $UnitGrade->name    = $name;
        $UnitGrade->level = $level;
        $UnitGrade->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $UnitGrade]);
    }

    /**
     * 删除等级
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delUnitGrade(Request $request){
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id     = !is_null($request->get('id')) ? $request->get('id') : 0;

        $unitGrade = UnitGrade::whereId($id)->first();
        if(!$unitGrade)
            return response()->json(['level' => 'error','message' => '删除失败']);

        $unitGrade->delete();

        return response()->json(['level' => 'success','message' => '删除成功']);
    }

    /**
     * 获取发票抬头列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInvoiceLookUpList(Request $request){
        $page       =!is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit      =!is_null($request->get('limit')) ? $request->get('limit') : 10;

        $page_info = [
            'page'  => $page,
            'limit' => $limit
        ];

        /** @var InvoiceLookUp $invoiceLookUp */
        $invoiceLookUpList = InvoiceLookUp::whereNull('deleted_at');

        $page_info['total'] = $invoiceLookUpList->count();

        $invoiceLookUpList = $invoiceLookUpList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($invoiceLookUpList) > 0){
            foreach($invoiceLookUpList as $invoiceLookUp){
                $invoiceLookUp->unit_name = '';
                $invoiceLookUp->unit_province = '';
                $invoiceLookUp->unit_city = '';
                $invoiceLookUp->unit_area = '';
                $invoiceLookUp->unit_address = '';
                $invoiceLookUp->unit_phone = '';

                $unitINfo = Units::whereId($invoiceLookUp->unit_id)->first();
                if($unitINfo){
                    $invoiceLookUp->unit_name = $unitINfo->name;
                    $invoiceLookUp->unit_phone = $unitINfo->contact_number;
                    $invoiceLookUp->unit_province = $unitINfo->province;
                    $invoiceLookUp->unit_city = $unitINfo->city;
                    $invoiceLookUp->unit_area = $unitINfo->area;
                    $invoiceLookUp->unit_address = $unitINfo->address;
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $invoiceLookUpList,'page_info' => $page_info]);
    }

    /**
     * 获取发票抬头详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInvoiceLookUpDetail(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $invoiceLookUp = InvoiceLookUp::whereId($id)->first();
        if($invoiceLookUp){
            $invoiceLookUp->unit_name = '';
            $invoiceLookUp->unit_province = '';
            $invoiceLookUp->unit_city = '';
            $invoiceLookUp->unit_area = '';
            $invoiceLookUp->unit_address = '';
            $invoiceLookUp->unit_phone = '';

            $unitINfo = Units::whereId($invoiceLookUp->unit_id)->first();
            if($unitINfo){
                $invoiceLookUp->unit_name = $unitINfo->name;
                $invoiceLookUp->unit_phone = $unitINfo->contact_number;
                $invoiceLookUp->unit_province = $unitINfo->province;
                $invoiceLookUp->unit_city = $unitINfo->city;
                $invoiceLookUp->unit_area = $unitINfo->area;
                $invoiceLookUp->unit_address = $unitINfo->address;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $invoiceLookUp]);
    }

    /**
     * 设置发票抬头
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setInvoiceLookUp(Request $request){
        $id             = !is_null($request->get('id')) ? $request->get('id') : 0;
        $unitId         = !is_null($request->get('unit_id')) ? $request->get('unit_id') : 0;
        $taxNumber      = !is_null($request->get('tax_number')) ? $request->get('tax_number') : '';
        $bankAccount    = !is_null($request->get('bank_account')) ? $request->get('bank_account') : '';
        $bankAccountNum = !is_null($request->get('bank_account_num')) ? $request->get('bank_account_num') : '';
        $emailAddress   = !is_null($request->get('email_address')) ? $request->get('email_address') : '';
        $isDefault      = !is_null($request->get('is_default')) ? $request->get('is_default') : 0;

        $unit = Units::whereId($unitId)->first();
        if(!$unit)
            return response()->json(['level' => 'error','message' => '单位不存在']);

        if(!in_array($unit->is_member_unit,[1,2]))
            return response()->json(['level' => 'error','message' => '请先完成单位入驻申请']);

        $isDefaultExist = InvoiceLookUp::whereUnitId($unit->id)->whereIsDefault(1)->first();
        if($isDefaultExist && $isDefault == 1){
            $isDefaultExist->is_default = 0;
            $isDefaultExist->save();
        }

        $newInvoiceLookUp = InvoiceLookUp::whereId($id)->first();
        if(!$newInvoiceLookUp)
            $newInvoiceLookUp = new InvoiceLookUp();

        $newInvoiceLookUp->unit_id              = $unit->id;
        $newInvoiceLookUp->Invoice_tax_number   = $taxNumber;
        $newInvoiceLookUp->bank_account         = $bankAccount;
        $newInvoiceLookUp->bank_account_num     = $bankAccountNum;
        $newInvoiceLookUp->email_address        = $emailAddress;
        $newInvoiceLookUp->is_default           = $isDefault;
        $newInvoiceLookUp->save();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $newInvoiceLookUp]);
    }

    /**
     * 删除发票抬头
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delInvoiceLookUp(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $invoiceLookUp = InvoiceLookUp::whereId($id)->first();
        if(!$invoiceLookUp)
            return response()->json(['level' => 'error','message' => '发票抬头不存在']);

        $invoiceLookUp->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $invoiceLookUp]);
    }

    /**
     * 发票记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInvoiceRecordList(Request $request){
        $page       = !is_null($request->get('page'))  ? $request->get('page') : 1;
        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $unitId     = !is_null($request->get('unit_id')) ? $request->get('unit_id') : 0;

        $page_info = [
            'page'  => $page,
            'limit' => $limit
        ];

        $invoiceRecordList = InvoiceRecord::whereNull('deleted_at');

        if($unitId != 0){
            $invoiceRecordList->whereUnitId($unitId);
        }

        $page_info['total'] = $invoiceRecordList->count();

        $invoiceRecordList = $invoiceRecordList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $invoiceRecordList,'page_info' => $page_info]);
    }
}
